package github.sf.fw.tools.db;

import com.alibaba.druid.DbType;
import com.mysql.cj.conf.ConnectionUrlParser;
import github.sf.fw.utils.StrUtil;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

public class DSProperty {
    private String url;
    private String username;
    private String password;
    private String driver;
    private String dbType;

    private String driverPath;

    private String databaseName;

    private Map<String, Object> meta = new LinkedHashMap<>();

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDriver() {
        return driver;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public String getDbType() {
        return dbType;
    }

    public void setDbType(String dbType) {
        this.dbType = dbType;
    }

    public String getDriverPath() {
        return driverPath;
    }

    public void setDriverPath(String driverPath) {
        this.driverPath = driverPath;
    }

    public String getDatabaseName() {
        return databaseName;
    }

    public void setDatabaseName(String databaseName) {
        this.databaseName = databaseName;
    }

    public Map<String, Object> getMeta() {
        return meta;
    }

    public void addMeta(String key, Object value) {
        if (meta == null) {
            meta = new LinkedHashMap<>();
        }
        meta.put(key, value);
    }

    public void setMeta(Map<String, Object> meta) {
        this.meta = meta;
    }

    public void changeDatabaseName(String databaseName) {
        Objects.requireNonNull(databaseName);
        setDatabaseName(databaseName);
        if (StrUtil.isEmpty(url)) {
            return;
        }
        if (DbType.mysql.equals(dbType)) {
            ConnectionUrlParser parser = ConnectionUrlParser.parseConnectionString(url);
            if (StrUtil.isEmpty(parser.getPath())) {
                if (url.endsWith("/")) {
                    this.url = url + databaseName;
                } else {
                    this.url = url + "/" + databaseName;
                }
            } else {
                //暂不处理
            }
        }
    }
}
